package com.lc.projects.unit.thread.part04.test1;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//线程执行器  ThreadPoolExecutor
public class Test1 {
	public static void main(String[] args) {
		Server server = new Server();
		for (int i = 0; i < 10; i++) {
			Task task = new Task("Task" + i);
			server.executeTask(task);
		}
		server.endServer();
	}
}

class Task implements Runnable {
	private String name;

	public Task(String name) {
		super();
		this.name = name;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " " + name + " start at:" + new Date());

		long duration = (long) (Math.random() * 10);
		System.out.println(Thread.currentThread().getName() + " " + name + " doing a job during " + duration);
		try {
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " " + name + " completed. " + new Date());
	}
}

class Server {
	private ThreadPoolExecutor executor;

	public Server() {
		// executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		// 固定大小的线程池
		executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
	}

	public void executeTask(Task task) {
		System.out.println("Server: a task arrived.");
		executor.execute(task);
		System.out.println("Server:pool size " + executor.getPoolSize());
		System.out.println("Server:Active count " + executor.getActiveCount());
		System.out.println("Server:Completed task " + executor.getCompletedTaskCount());
	}

	public void endServer() {
		executor.shutdown();
	}
}